import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'

import styles from '../../styles/Cars.module.scss'
import { useState } from 'react'

import router from 'next/router'
import { Booklist } from '../../services/book.service'
import { BookService } from '../../services'
import { Dialog, Toast } from 'antd-mobile'
import { Winicon } from '../../components/Icon'
import Empty from '../../components/Empty'
import Back from '../../components/Back'

interface Props {
  res: Booklist
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const token = ctx.req.cookies.token
  const result = await BookService.carlist(token)
  if (result.stat === 'OK') {
    return {
      props: {
        res: result
      }
    }
  }
  return {
    redirect: {
      destination: '/login',
      permanent: false
    }
  }
}


const Cars: NextPage<Props> = ({ res }) => {
  const [cars, setCars] = useState(res.data.list)
  const [choices, setChoice] = useState<string[]>([])
  const [money, setMoney] = useState<number>(0)

  async function remove(id: string, index: number) {
    if (await Dialog.confirm({ content: '确认移除出购物车' })) {
      const res = await BookService.dealcar(id, false)
      if (res.stat === 'OK') {
        cars.splice(index, 1)
        setCars(cars.map(v => v))
        removeChoice(id)
        Toast.show({ content: <Winicon text={res.msg} /> })
      }
    }
  }

  function addDingdan() {
    router.push({ pathname: '/cart/checkout', query: { choices, money } })
  }

  function addChoice(id: string) {
    if (choices.includes(id)) return
    choices.push(id)
    setChoice(choices.map(v => v))
  }
  function removeChoice(id: string) {
    if (choices.includes(id)) {
      const idx = choices.indexOf(id)
      choices.splice(idx, 1)
      setChoice(choices.map(v => v))
    }
  }

  function dealPrice(price: number) {
    setMoney(money + price)
  }

  return (
    <div className="page">
      <Head>
        <title>购物车页</title>
      </Head>
      <div className="wrapRaw">
        <header className={styles.header}>
          <h2>购物车最多添加十件商品</h2>
        </header>
        {
          cars.map((item, idx) =>
            <div className={styles.catlist} key={item._id}>
              <div className={styles.item}>
                <div className={styles.select}>
                  {
                    choices.includes(item._id) ? <i
                      className={styles.xuanze + ' iconfont icon-xuanze'}
                      onClick={() => {
                        removeChoice(item._id)
                        dealPrice(-item.allprice)
                      }}
                    >
                    </i> : <div
                      className={styles.chose}
                      onClick={() => {
                        addChoice(item._id)
                        dealPrice(item.allprice)
                      }}
                    ></div>
                  }
                </div>
                <div className={styles.info} onClick={() => router.push(`/goods/${item.book._id}`)}>
                  <img src={item.book.banner[0]} alt="" />
                  <div className={styles.content}>
                    <h4>{item.book.title}</h4>
                    <p>{item.names.map((v, i) => <i key={i}>{v}&nbsp;</i>)}</p>
                    <span>¥ {item.allprice}</span>
                  </div>
                  <div className={styles.del}>
                    <div
                      className='iconfont icon-shanchu1'
                      onClick={(e) => {
                        e.stopPropagation()
                        remove(item._id, idx)
                      }} />
                  </div>
                </div>
              </div>
            </div>
          )
        }
        {cars.length === 0 && <Empty />}
      </div>
      <div className={styles.bottom}>
        <div className={styles.nums}>
          {
            (cars.length !== 0 && choices.length === cars.length) ? <i
              className={styles.xuanze + ' iconfont icon-xuanze'}
              onClick={() => {
                setChoice([])
                setMoney(0)
              }}
            >
            </i> : <div
              className={styles.chose}
              onClick={() => {
                setChoice(cars.map(v => v._id))
                setMoney(cars.reduce((a, b) => {
                  return a + b.allprice
                }, 0))
              }}
            ></div>
          }
          <span>已选 {choices.length}</span>
        </div>
        <div className={styles.money}>
          ¥{Math.abs(money).toFixed(2)}
        </div>
        <button className={styles.done}
          disabled={choices.length === 0}
          onClick={addDingdan}>结算</button>
      </div>
      <Back />
    </div>
  )
}

export default Cars
